<?php

/**
 * Description of Sqlite
 *
 * @author ZzanZhang
 */
class Sqlite {

	public $databaseName;
	public $databasePath;
	public $handle;
	public $errorMessage = '';
	static public $instance = null;

	public function __construct($databaseName) {
		$this->databaseName = $databaseName;

		$this->databasePath = PATH_SQLITE . $databaseName . '.s3db';

		$this->handle = new Sqlite3($this->databasePath);
	}

	public function exec($query) {
		if (!$this->handle->exec($query)) {
			$this->errorMessage = $this->handle->lastErrorMsg();
			return false;
		}

		return true;
	}

	public function query($query) {
		if (!($result = $this->handle->query($query))) {
			$this->errorMessage = $this->handle->lastErrorMsg();
			return false;
		}

		return $result;
	}

	public function getAll($query, $mode = SQLITE3_ASSOC) {
		if(!($result = $this->query($query)))
			return array();
		$data = array();
		while ($row = $result->fetchArray($mode)){
			$data[] = $row;
		}
		$result->finalize();
		return $data;
	}
	
	public function getOne($query, $mode = SQLITE3_ASSOC){
		if(!($result = $this->query($query))){
			return false;
		}
		$data = $result->fetchArray($mode);
		$result->finalize();
		return $data;
	}

	public function set($table, $data,  $id = 0){
		if($id > 0) {
			$query = $this->buildUpdateSql($table, $data, $id);
			return $this->exec($query);
		} else {
			$query = $this->buildInsertSql($table, $data);
			$this->exec($query);
			return $this->handle->lastInsertRowID();
		}
		
	}

	private function buildUpdateSql($table, $data, $id){
		$fields = array();
		foreach($data as $k => $v){
			if(is_numeric($v)){
				$fields[] =  "`{$k}`={$v}";
			}else{
				$v = $this->handle->escapeString($v);
				$fields[] =  "`{$k}`='{$v}'";
			}
		}
		return "UPDATE `{$table}` SET " . implode(",", $fields) . " WHERE `id`={$id}";
	}

	private function buildInsertSql($table, $data) {
		$keys = $values = array();
		foreach ($data as $k => $v) {
			$keys[] = "`{$k}`";
			if(is_numeric($v)){
				$values[] = $v;
			}else{
				$v = $this->handle->escapeString($v);
				$values[] = "'{$v}'";
			}
		}
		return "INSERT INTO `{$table}` ( " . implode(',', $keys) . " ) VALUES ( " . implode(',', $values) . " )";
	}

	public function getTables() {
		$query = "SELECT name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY name;";
		$tables = $this->getAll($query);
		foreach($tables as $key => $table)
			if($table === false)
				unset($tables[$key]);
		return $tables;
	}
	
	public function getColumns($table){
		if(!($result = $this->query("SELECT * FROM {$table};")))
			return false;
		$cols = $result->numColumns();
		$data = array();
		for($i = 0; $i < $cols; $i++)
			$data[] = $result->columnName($i);
		return $data;
	}
	
	public function truncate($table) {
		$table = $this->handle->escapeString($table);
		$this->exec("delete from `{$table}`;");
		$this->exec("delete from sqlite_sequence where name='{$table}';");
		//delete from goodsImage;delete from sqlite_sequence where name='goodsImage';
		//update sqlite_sequence set seq = [起始记录值] where name = 'your_table_name' ; 
	}

	public function escape($string) {
		return $this->handle->escapeString($string);
	}

	public function tableExists($table) {
		if(!($tables = $this->getTables())){
			return false;
		}
		
		return in_array($table, $tables);
	}

	public function __destruct() {
		$this->handle->close();
	}

}

?>
